package com.lz.controller;

import com.lz.entity.ProductCategory;
import com.lz.entity.ProductInfo;
import com.lz.service.ProductCategoryService;
import com.lz.service.ProductInfoService;
import com.lz.utils.ResultVOUtil;
import com.lz.vo.ProductInfoVO;
import com.lz.vo.ProductVO;
import com.lz.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by lz on 2018/8/10.
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @RequestMapping("/list")
    public ResultVO list(){
        //1.查询所有上架商品
        List<ProductInfo> upAll = productInfoService.findUpAll();

        //2.查询类目一次性查询
        //传统方法 for
        /*List<Integer> categoryTypeList = new ArrayList<>();
        for (ProductInfo productInfo : upAll) {
            categoryTypeList.add(productInfo.getCategoryType());
        }*/
        //精简做法(java8，lambda)
        List<Integer> categoryTypeList = upAll.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());

        List<ProductCategory> byCategoryTypeIn = productCategoryService.findByCategoryTypeIn(categoryTypeList);

        //3.数据封装
        List<ProductVO> productVOS = new ArrayList<>();
        for (ProductCategory productCategory:byCategoryTypeIn){
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());

            List<ProductInfoVO> voList = new ArrayList<>();
            for (ProductInfo productInfo:upAll){
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    voList.add(productInfoVO);
                }
            }

            productVO.setProductInfoVOList(voList);
            productVOS.add(productVO);
        }


        return ResultVOUtil.success(productVOS);
    }
}
